package com.ias.business.testbiz.service.impl;

import com.ias.business.testbiz.entity.TestBizEntity;
import com.ias.business.testbiz.mapper.TestBizMapper;
import com.ias.business.testbiz.service.TestBizMapperDemoService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 测试业务Mapper演示服务实现类
 * 展示如何使用Mapper.xml中定义的自定义SQL方法
 * 
 * @author IAS Team
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TestBizMapperDemoServiceImpl implements TestBizMapperDemoService {

    private final TestBizMapper testBizMapper;

    @Override
    public TestBizEntity demonstrateBasicQuery(String bizCode) {
        log.info("演示基础查询功能，业务编码：{}", bizCode);
        
        if (!StringUtils.hasText(bizCode)) {
            log.warn("业务编码不能为空");
            return null;
        }

        // 使用自定义SQL查询
        TestBizEntity entity = testBizMapper.selectByBizCode(bizCode);
        
        if (entity != null) {
            log.info("查询成功，业务名称：{}", entity.getBizName());
        } else {
            log.info("未找到对应的业务记录");
        }
        
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> demonstrateBatchOperations(List<TestBizEntity> entities) {
        log.info("演示批量操作功能，批量插入{}条记录", entities.size());
        
        Map<String, Object> result = new HashMap<>();
        
        if (CollectionUtils.isEmpty(entities)) {
            result.put("success", false);
            result.put("message", "实体列表不能为空");
            return result;
        }

        try {
            // 批量插入
            int insertCount = testBizMapper.batchInsert(entities);
            log.info("批量插入完成，成功插入{}条记录", insertCount);
            
            // 获取插入后的ID列表
            List<Long> ids = entities.stream()
                    .map(TestBizEntity::getId)
                    .collect(Collectors.toList());
            
            // 批量查询验证
            List<TestBizEntity> insertedEntities = testBizMapper.selectByIds(ids);
            log.info("批量查询验证，查询到{}条记录", insertedEntities.size());
            
            result.put("success", true);
            result.put("insertCount", insertCount);
            result.put("verifyCount", insertedEntities.size());
            result.put("insertedIds", ids);
            result.put("message", "批量操作成功");
            
        } catch (Exception e) {
            log.error("批量操作失败", e);
            result.put("success", false);
            result.put("message", "批量操作失败：" + e.getMessage());
            throw e; // 抛出异常以触发事务回滚
        }
        
        return result;
    }

    @Override
    public Map<String, Object> demonstrateConditionalQuery(String keyword, Integer bizType, Integer status) {
        log.info("演示条件查询功能，关键词：{}，业务类型：{}，状态：{}", keyword, bizType, status);
        
        Map<String, Object> result = new HashMap<>();
        
        // 1. 关键词搜索
        List<TestBizEntity> keywordResults = testBizMapper.selectByKeyword(keyword);
        log.info("关键词搜索结果：{}条", keywordResults.size());
        
        // 2. 业务类型查询
        List<TestBizEntity> typeResults = null;
        if (bizType != null) {
            typeResults = testBizMapper.selectByBizType(bizType);
            log.info("业务类型查询结果：{}条", typeResults.size());
        }
        
        // 3. 复合条件查询
        List<TestBizEntity> compositeResults = testBizMapper.selectPageWithCondition(
                null, keyword, null, bizType, status, 0, "create_time DESC"
        );
        log.info("复合条件查询结果：{}条", compositeResults.size());
        
        result.put("keywordResults", keywordResults);
        result.put("keywordCount", keywordResults.size());
        if (typeResults != null) {
            result.put("typeResults", typeResults);
            result.put("typeCount", typeResults.size());
        }
        result.put("compositeResults", compositeResults);
        result.put("compositeCount", compositeResults.size());
        
        return result;
    }

    @Override
    public Map<String, Object> demonstrateStatisticsAnalysis(Integer bizType) {
        log.info("演示统计分析功能，业务类型：{}", bizType);
        
        Map<String, Object> result = new HashMap<>();
        
        // 1. 整体统计
        Map<String, Object> overallStats = testBizMapper.selectStatistics(bizType);
        log.info("整体统计结果：{}", overallStats);
        
        // 2. 按业务类型统计
        List<Map<String, Object>> typeStats = testBizMapper.countByBizType(null);
        log.info("按业务类型统计结果：{}", typeStats);
        
        // 3. 活跃业务数量
        Long activeCount = testBizMapper.countActiveTestBiz();
        log.info("活跃业务数量：{}", activeCount);
        
        result.put("overallStatistics", overallStats);
        result.put("typeStatistics", typeStats);
        result.put("activeCount", activeCount);
        
        // 计算一些派生指标
        if (overallStats != null) {
            Long totalCount = (Long) overallStats.get("totalCount");
            Long activeCountFromStats = (Long) overallStats.get("activeCount");
            
            if (totalCount != null && totalCount > 0) {
                double activeRate = (activeCountFromStats != null ? activeCountFromStats.doubleValue() : 0) / totalCount * 100;
                result.put("activeRate", String.format("%.2f%%", activeRate));
            }
        }
        
        return result;
    }

    @Override
    public List<TestBizEntity> demonstrateTimeRangeQuery(LocalDateTime startTime, LocalDateTime endTime) {
        log.info("演示时间范围查询，开始时间：{}，结束时间：{}", startTime, endTime);
        
        List<TestBizEntity> results = testBizMapper.selectByTimeRange(startTime, endTime);
        
        log.info("时间范围查询结果：{}条记录", results.size());
        
        // 统计时间分布
        if (!results.isEmpty()) {
            LocalDateTime minTime = results.stream()
                    .map(TestBizEntity::getCreateTime)
                    .min(LocalDateTime::compareTo)
                    .orElse(null);
            LocalDateTime maxTime = results.stream()
                    .map(TestBizEntity::getCreateTime)
                    .max(LocalDateTime::compareTo)
                    .orElse(null);
            
            log.info("实际时间范围：{} 到 {}", minTime, maxTime);
        }
        
        return results;
    }

    @Override
    public List<TestBizEntity> demonstrateDynamicSQL(TestBizEntity entity) {
        log.info("演示动态SQL功能，查询条件：{}", entity);
        
        // 使用动态SQL进行条件查询
        List<TestBizEntity> results = testBizMapper.selectPageWithCondition(
                entity.getId(),
                entity.getBizName(),
                entity.getBizCode(),
                entity.getBizType(),
                entity.getStatus(),
                entity.getDeleted(),
                "create_time DESC"
        );
        
        log.info("动态SQL查询结果：{}条记录", results.size());
        
        return results;
    }

    @Override
    public Map<String, Object> demonstratePagination(String keyword, Integer bizType, int pageNum, int pageSize) {
        log.info("演示分页查询功能，关键词：{}，业务类型：{}，页码：{}，页大小：{}", keyword, bizType, pageNum, pageSize);
        
        Map<String, Object> result = new HashMap<>();
        
        // 计算偏移量
        int offset = (pageNum - 1) * pageSize;
        
        // 分页查询数据
        List<TestBizEntity> pageData = testBizMapper.selectByPage(keyword, bizType, null, offset, pageSize);
        
        // 查询总数
        Long totalCount = testBizMapper.selectCountByPage(keyword, bizType, null);
        
        // 计算总页数
        int totalPages = (int) Math.ceil((double) totalCount / pageSize);
        
        log.info("分页查询结果：当前页{}条，总数{}条，总页数{}页", pageData.size(), totalCount, totalPages);
        
        result.put("data", pageData);
        result.put("pageNum", pageNum);
        result.put("pageSize", pageSize);
        result.put("totalCount", totalCount);
        result.put("totalPages", totalPages);
        result.put("hasNext", pageNum < totalPages);
        result.put("hasPrevious", pageNum > 1);
        
        return result;
    }

    @Override
    public boolean demonstrateUniquenessCheck(String bizCode, Long excludeId) {
        log.info("演示业务编码唯一性检查，业务编码：{}，排除ID：{}", bizCode, excludeId);
        
        Boolean exists = testBizMapper.existsByBizCode(bizCode, excludeId);
        
        log.info("唯一性检查结果：{}", exists ? "已存在" : "不存在");
        
        return !exists; // 返回true表示可以使用（不存在冲突）
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> demonstrateBatchStatusUpdate(List<Long> ids, Integer status) {
        log.info("演示批量状态更新，ID列表：{}，新状态：{}", ids, status);
        
        Map<String, Object> result = new HashMap<>();
        
        if (CollectionUtils.isEmpty(ids)) {
            result.put("success", false);
            result.put("message", "ID列表不能为空");
            return result;
        }

        try {
            // 批量更新状态
            int updateCount = testBizMapper.batchUpdateStatus(ids, status);
            
            // 验证更新结果
            List<TestBizEntity> updatedEntities = testBizMapper.selectByIds(ids);
            long verifyCount = updatedEntities.stream()
                    .filter(entity -> entity.getStatus().equals(status))
                    .count();
            
            log.info("批量状态更新完成，影响{}行，验证{}行状态正确", updateCount, verifyCount);
            
            result.put("success", true);
            result.put("updateCount", updateCount);
            result.put("verifyCount", verifyCount);
            result.put("message", "批量状态更新成功");
            
        } catch (Exception e) {
            log.error("批量状态更新失败", e);
            result.put("success", false);
            result.put("message", "批量状态更新失败：" + e.getMessage());
            throw e;
        }
        
        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> demonstrateSoftDelete(List<Long> ids) {
        log.info("演示软删除功能，ID列表：{}", ids);
        
        Map<String, Object> result = new HashMap<>();
        
        if (CollectionUtils.isEmpty(ids)) {
            result.put("success", false);
            result.put("message", "ID列表不能为空");
            return result;
        }

        try {
            // 记录删除前的数据
            List<TestBizEntity> beforeDelete = testBizMapper.selectByIds(ids);
            
            // 执行软删除
            int deleteCount = testBizMapper.batchSoftDelete(ids);
            
            // 验证删除结果（使用MyBatis-Plus的selectBatchIds，它会自动过滤已删除的记录）
            List<TestBizEntity> afterDelete = testBizMapper.selectBatchIds(ids);
            
            log.info("软删除完成，影响{}行，删除前{}条，删除后{}条", deleteCount, beforeDelete.size(), afterDelete.size());
            
            result.put("success", true);
            result.put("deleteCount", deleteCount);
            result.put("beforeCount", beforeDelete.size());
            result.put("afterCount", afterDelete.size());
            result.put("message", "软删除成功");
            
        } catch (Exception e) {
            log.error("软删除失败", e);
            result.put("success", false);
            result.put("message", "软删除失败：" + e.getMessage());
            throw e;
        }
        
        return result;
    }
} 